package com.cocos.game

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Log
import com.appsflyer.AppsFlyerConversionListener
import com.appsflyer.AppsFlyerLib
import com.appsflyer.attribution.AppsFlyerRequestListener
import com.cocos.service.SDKWrapper.SDKInterface
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class AppsFlyerCocosSDK : SDKInterface, AppsFlyerConversionListener {

    companion object {
        @SuppressLint("StaticFieldLeak")
        var instance: AppsFlyerCocosSDK? = null
        private const val TAG = "AppsFlyerCocosSDK"

        private val developer_devices = listOf("039bf5ef49752a55")
    }

    var activity: Activity? = null

    var devKey = "euAYgsBifJq5rDeqPoL2Pj"

    override fun init(context: Context?) {
        this.activity = context as Activity
        Log.i(TAG, "init: $TAG")
        instance = this
        JsbSDK.onMsg("AppsFlyerCocosSDK.logEvent") { args -> this.logEvent(args) }
        initialize()
    }

    private fun initialize() {
        Log.i(TAG, "initialize: ")
        AppsFlyerLib.getInstance().setDebugLog(true)
        AppsFlyerLib.getInstance().init(devKey, this, this.activity!!)
        AppsFlyerLib.getInstance().waitForCustomerUserId(true)
        AppsFlyerLib.getInstance().start(this.activity!!, devKey, object :AppsFlyerRequestListener {
            override fun onSuccess() {
                Log.d(TAG, "Launch sent successfully")
            }
            override fun onError(errorCode: Int, errorDesc: String) {
                Log.d(TAG, "Launch failed to be sent:\n" +
                        "Error code: " + errorCode + "\n"
                        + "Error description: " + errorDesc)
            }
        })
    }

    fun setCustomerId(customId: String) {
        AppsFlyerLib.getInstance().setCustomerIdAndLogSession(customId, this.activity!!)
    }

    override fun onConversionDataSuccess(p0: MutableMap<String, Any>?) {
        JsbSDK.sendMsg("AppsFlyerSDKManager.responseConversionData", p0)
    }

    override fun onConversionDataFail(p0: String?) {
        Log.d(TAG, "onConversionDataFail: $p0")
    }

    override fun onAppOpenAttribution(p0: MutableMap<String, String>?) {
        Log.d(TAG, "onAppOpenAttribution: $p0")
    }

    override fun onAttributionFailure(p0: String?) {
        Log.d(TAG, "onAttributionFailure: $p0")
    }

    private fun logEvent(args: String) {
        val argMap: Map<String, Any> = Gson().fromJson(args, object : TypeToken<Map<String, Any>>() {}.type);
        val eventName = argMap["eventName"] as? String
        Log.i(TAG, "logEvent: $eventName")
        AppsFlyerLib.getInstance().logEvent(this.activity!!, eventName, HashMap())
    }

}